<template>
  <div class="analytics-container" v-loading="analyticsStore.loading">
    <h2 class="analytics-title">电影数据分析</h2>
    
    <el-row :gutter="20">
      <!-- 评分分布 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>评分分布</span>
            </div>
          </template>
          <div ref="ratingChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 类型分布 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>类型分布</span>
            </div>
          </template>
          <div ref="genreChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row v-if="analyticsStore.error">
      <el-col :span="24">
        <el-alert :title="analyticsStore.error" type="error" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useAnalyticsStore } from '@/stores/analytics'
import * as echarts from 'echarts'

const analyticsStore = useAnalyticsStore()
const ratingChart = ref(null)
const genreChart = ref(null)
let ratingChartInstance = null
let genreChartInstance = null

// 初始化评分分布图表
const initRatingChart = () => {
  if (ratingChart.value && analyticsStore.ratingDistribution.length > 0) {
    ratingChartInstance = echarts.init(ratingChart.value)
    const option = {
      title: {
        text: '电影评分分布',
        left: 'center',
        top: 10,
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#374151'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}: {c}部'
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: analyticsStore.ratingDistribution.map(item => `${item.rating}分`),
        axisLabel: {
          interval: 0,
          color: '#4b5563'
        }
      },
      yAxis: {
        type: 'value',
        name: '电影数量',
        nameTextStyle: {
          color: '#4b5563'
        },
        axisLabel: {
          color: '#4b5563'
        },
        splitLine: {
          lineStyle: {
            color: '#e5e7eb'
          }
        }
      },
      series: [{
        data: analyticsStore.ratingDistribution.map(item => item.count),
        type: 'bar',
        barWidth: '40%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#60a5fa' },
            { offset: 1, color: '#3b82f6' }
          ]),
          borderRadius: [6, 6, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#93c5fd' },
              { offset: 1, color: '#60a5fa' }
            ])
          }
        }
      }]
    }
    ratingChartInstance.setOption(option)
  }
}

// 初始化类型分布图表
const initGenreChart = () => {
  if (genreChart.value && analyticsStore.genreDistribution.length > 0) {
    genreChartInstance = echarts.init(genreChart.value)
    const colors = [
      '#6366f1', '#22c55e', '#f59e0b', '#ef4444', '#8b5cf6',
      '#06b6d4', '#f97316', '#3b82f6', '#ec4899', '#10b981',
      '#84cc16', '#14b8a6', '#f43f5e', '#8b5cf6', '#6366f1'
    ]
    const total = analyticsStore.genreDistribution.reduce((sum, item) => sum + item.count, 0)
    
    const option = {
      backgroundColor: '#ffffff',
      title: {
        text: '电影类型分布',
        left: 'center',
        top: 10,
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#374151'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          const item = analyticsStore.genreDistribution.find(i => i.genre === params.name)
          if (!item) return ''
          const percentage = ((item.count / total) * 100).toFixed(1)
          return `${item.genre}<br/>数量: ${item.count}部 (${percentage}%)<br/>平均评分: ${item.average_rating}分`
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderWidth: 0,
        padding: [8, 12],
        textStyle: {
          color: '#fff',
          fontSize: 13
        }
      },
      legend: {
        orient: 'vertical',
        right: '5%',
        top: 'center',
        itemWidth: 10,
        itemHeight: 10,
        itemGap: 15,
        formatter: (name) => {
          const item = analyticsStore.genreDistribution.find(i => i.genre === name)
          return item ? `${name} (${item.count}部)` : ''
        },
        textStyle: {
          color: '#4b5563',
          fontSize: 13,
          padding: [0, 0, 0, 4]
        }
      },
      series: [{
        name: '电影类型',
        type: 'pie',
        radius: ['20%', '70%'],
        center: ['40%', '50%'],
        startAngle: 0,
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: analyticsStore.genreDistribution.map((item, index) => ({
          name: item.genre,
          value: item.count,
          itemStyle: {
            color: colors[index],
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 3
          }
        })),
        emphasis: {
          scale: true,
          scaleSize: 10,
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          }
        },
        universalTransition: true,
        animationType: 'expansion',
        animationDuration: 1000,
        animationEasing: 'cubicOut',
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 3
        },
        gapWidth: 8  // 扇区间隙
      }]
    }
    genreChartInstance.setOption(option)
  }
}

// 监听窗口大小变化
const handleResize = () => {
  ratingChartInstance?.resize()
  genreChartInstance?.resize()
}

// 监听数据变化
watch(() => analyticsStore.ratingDistribution, initRatingChart, { deep: true })
watch(() => analyticsStore.genreDistribution, initGenreChart, { deep: true })

// 组件挂载时初始化
onMounted(async () => {
  await analyticsStore.fetchAnalytics()
  // 等待 DOM 更新后初始化图表
  setTimeout(() => {
    initRatingChart()
    initGenreChart()
  }, 0)
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  ratingChartInstance?.dispose()
  genreChartInstance?.dispose()
})
</script>

<style scoped>
.analytics-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.analytics-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.chart-card {
  margin-bottom: 20px;
  height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 400px;
  position: relative;
  padding: 10px;
}

@media (max-width: 768px) {
  .chart-container {
    height: 300px;
  }
  
  .chart-card {
    height: 400px;
  }
}
</style> 